package com.zxt.content.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.zxt.content.common.Bean.BUserInfoApiVO;
import com.zxt.content.common.Bean.Result;
import com.zxt.content.common.utils.ResultCode;
import com.zxt.content.common.utils.UserContainer;
import com.zxt.content.common.utils.UserUtil;
import com.zxt.content.common.utils.ZXTCollectionsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Objects;

@Component
@Slf4j
public class ProjectInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 打印日志
            log.info("all-content requestUri：{},contextPath：{},parameterNames：{}", request.getRequestURI(), request.getContextPath(), JSON.toJSONString(request.getParameterMap()));

            BUserInfoApiVO user = UserUtil.getUser(request);
            if (Objects.nonNull(user)) {
                //存储进ThreadLocal
                UserContainer.putUserInfo(user);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            returnErrorJson(response, JSON.toJSONString(Result.newError(ResultCode.SYS_ERROR)));
            return false;
        }
    }


    public void returnErrorJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
